/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package thread;

import form.GUI;


import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Barbar
 */
public class FileCheckThread implements Runnable {
     
static <T> WatchEvent<T> castEvent(WatchEvent<?> event) {
    return (WatchEvent<T>)event;
}

    private static final FileCheckThread INSTANCE = null;
//    Path path = Paths.get(GUI.PathForShare);
    Path _directotyToWatch = Paths.get("C:\\defaultSharedFiles");
  

    public void run() {
         WatchService watcherSvc = null;
         WatchKey watchKey = null;
        try {
            watcherSvc = FileSystems.getDefault().newWatchService();
           watchKey  = _directotyToWatch.register(watcherSvc,ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ex) {
            Logger.getLogger(FileCheckThread.class.getName()).log(Level.SEVERE, null, ex);
        }
   
       
//  File file = new File(GUI.PathForShare);
    while (true) {
            try {
                watchKey=watcherSvc.take();
            } catch (InterruptedException ex) {
                Logger.getLogger(FileCheckThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        for (WatchEvent<?> event: watchKey.pollEvents()) {
            WatchEvent<Path> watchEvent = castEvent(event);
            System.out.println(event.kind().name().toString() + " "
        + _directotyToWatch.resolve(watchEvent.context()));
            
      GUI.listingTree();
            GUI.lf.listFile(".json");
            System.out.println("odczytano z jsonów");
            GUI.listingFlag = true;
             System.out.println("ListingFlag " + GUI.listingFlag);
            watchKey.reset();
        }
    }
    
    }

    public static FileCheckThread getInstance() {
        return FileCheckThread.FileChekcThreadHolder.INSTANCE;
              
    }

    private static class FileChekcThreadHolder {

        private static final FileCheckThread INSTANCE = new FileCheckThread();
    }
}
